package com.rxyb.trade.utils.yinshang;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;

/**
 * DEMO 中的 NotifyUtilTest
 * 
 * @coder duyh,@auth duyh
 * @date Apr 17, 2019
 */
public class YinShangSignUtils {

	// 构建签名字符串
	public static String buildSignString(Map<String, String> params) {

		if (params == null || params.size() == 0) {
			return "";
		}

		List<String> keys = new ArrayList<>(params.size());

		for (String key : params.keySet()) {
			if ("sign".equals(key))
				continue;
			if (StringUtils.isEmpty(params.get(key)))
				continue;
			keys.add(key);
		}

		Collections.sort(keys);

		StringBuilder buf = new StringBuilder();

		for (int i = 0; i < keys.size(); i++) {
			String key = keys.get(i);
			String value = params.get(key);

			if (i == keys.size() - 1) {// 拼接时，不包括最后一个&字符
				buf.append(key + "=" + value);
			} else {
				buf.append(key + "=" + value + "&");
			}
		}

		return buf.toString();
	}

	// 根据编码类型获得签名内容byte[]
	public static byte[] getContentBytes(String content) {
		try {
			return content.getBytes("UTF-8");
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("签名过程中出现错误");
		}
	}

	/**
	 * 验签
	 */
	public static boolean checkSign2(String md5Key, Map<String, String> params) {

		// 获取params中的sign
		String originalSign = params.get("sign");
		System.out.println("原有签名sign：" + originalSign);
		System.out.println("获取请求中的原有map为:" + params);

		// 生成待签字串 和 sign
		String preStrNew = buildSignString(params); // 把数组所有元素，按照“参数=参数值”的模式用“&”字符拼接成字符串
		String preStrNew_md5Key = preStrNew + md5Key;
		System.out.println("生成待签字串为：" + preStrNew_md5Key);

		String sign = DigestUtils.md5Hex(getContentBytes(preStrNew_md5Key)).toUpperCase();
		System.out.println("计算签名sign为：" + sign);

		// 返回结果
		return originalSign.equals(sign);
	}

}
